<template>
	<el-dialog title="提示" :visible.sync="shadown" width="50%" :before-close="handleClose">
		<el-form :model="roleInfo" :rules="rules" ref="roleInfo">
			<table style="width: 100%;">
				<tr>
					<td class="title">角色名称:</td>
					<td class="content">
						<el-form-item prop="roleName">
							<el-input v-model="roleInfo.roleName"></el-input>
						</el-form-item>
					</td>
				</tr>

				<tr>
					<td class="title">角色描述:</td>
					<td class="content">
						<el-form-item prop="roleDesc">
							<el-input v-model="roleInfo.roleDesc"></el-input>
						</el-form-item>
					</td>
				</tr>
				<tr>
					<td colspan="2">
						<el-row>
							<el-tree :data="allPermissions" show-checkbox node-key="permissionDesc" ref="tree" :props="defaultProps">
							</el-tree>
						</el-row>
					</td>
				</tr>

			</table>
		</el-form>

		<span slot="footer" class="dialog-footer">
	        <el-button @click="handleClose">取 消</el-button>
	        <el-button type="primary" @click="addnewone">确 定</el-button>
	    </span>
	</el-dialog>
</template>

<script>
	export default {
		props: ["shadown"],
		data() {
			// 自定义的验证规则

			return {

				defaultProps: {
					children: 'children',
					label: 'label',
				},
				roleInfo: { roleName: '', roleDesc: '', permissions: [] },
				rules: {
					roleName: [
						{ required: true, message: '请输入角色名称', trigger: 'blur' },
						{ min: 2, message: '名称最少两个字符', trigger: 'blur' }
					],
					roleDesc: [
						{ required: true, message: '请输入角色描述', trigger: 'blur' },
						{ min: 4, message: '描述不能少于4个字', trigger: 'blur' }
					]
				}

			}
		},

		computed: {
			allPermissions() {

				return this.$store.getters.allPermissions;
			},

		},

		methods: {
			handleClose() {
				this.$parent.shadown = false;
			},
			addnewone() {
				
				var permission = [];
				this.$refs.tree.getCheckedNodes().forEach((item) => {
					
					permission.push(item._id)
				})
				this.roleInfo.permissions = permission;
				this.$refs['roleInfo'].validate((valid) => {
					if(valid) {
						this.$http.post(this.$api.insertRole, this.roleInfo)
							.then((res) => {
								this.$message({
									message: res.data.message,
									type: res.data.success ? "success" : "danger"
								});
								this.handleClose();
								this.$store.dispatch("loadallroles", { api: this.$api.allRoles });
							})
					} else {
						console.log('error submit!!');
						return false;
					}
				});

			}

		}

	}
</script>

<style lang="scss" scoped>
	tr {
		width: 100%;
		height: 62px;
		line-height: 40px;
		padding: 5px;
	}
	
	.title {
		width: 30%;
	}
	
	.content {
		width: 120%;
	}
	
	.xiaoxiang {
		text-align: left;
		padding-left: 30px;
	}
	
	.xuanzhe {
		display: flex;
		flex-direction: column;
		justify-content: flex-start;
	}
</style>